package com.t8;
import static net.mindview.util.Print.*;

/**
 * Created by xuyiwei on 2018/7/19.
 */
class Shared{
    private int refcount = 0;
    private static long counter = 0;
    private long id = counter++;
    public Shared() {
        System.out.println("Create "+this);
    }
    public void addRef(){this.refcount++;}
    public void dispose(){
        if(--refcount==0){
            print("Dispose "+this);
        }
    }
    protected void finalize() {
        if(refcount != 0)
            print("Error: object is not properly cleaned-up!");
    }
}
class Composing{
    private Shared shared;
    private static long counter = 0;
    private long id = counter++;
    public Composing(Shared shared) {
        System.out.println("Create "+this);
        this.shared = shared;
        shared.addRef();
    }
    public void dispose(){
        System.out.println("dispose "+this);
        shared.dispose();
    }

    @Override
    public String toString() {
        return "Composing " +id;
    }
}
public class ReferenceCounting {
    public static void main(String[] args) {
        System.gc();
        Shared shared = new Shared();
        Composing[] composing = {
                new Composing(shared),
                new Composing(shared),
                new Composing(shared)
        };
        for(Composing c : composing){
            c.dispose();
        }
        //第一次进行清理没有执行finalize()方法是因为上面数组的对象
        //明确指向了相对应的引用 就是每个对象的计数器都大于0
        System.gc();
        // Verify failure:
        new Composing(new Shared());
        //这里执行是因为对象没有明确指向引用，因此引用计数器是0，是需要被回收的
        System.gc();
    }

}
